package com.yuanfeng.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.business.dto.GateOpenDTO;
import com.yuanfeng.business.dto.GateQueryStoreDTO;
import com.yuanfeng.business.dto.GoodsGateDTO;
import com.yuanfeng.business.entity.ShopGateEntity;
import com.yuanfeng.business.entity.ShopGateGoodsBaseEntity;
import com.yuanfeng.business.feign.BaseServiceClient;
import com.yuanfeng.business.mapper.ShopGateGoodsBaseMapper;
import com.yuanfeng.business.mapper.ShopGateMapper;
import com.yuanfeng.business.service.ShopGateService;
import com.yuanfeng.business.vo.GoodsGateVO;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.goods.GoodsInfoDTO;
import com.yuanfeng.commoms.dto.shop.GateStoreUpdateDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.WapGoodsSaleSumUpdateVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class ShopGateServiceImpl extends ServiceImpl<ShopGateMapper, ShopGateEntity>
    implements ShopGateService{

    @Autowired
    private BaseServiceClient baseServiceClient;
    @Resource
    private ShopGateGoodsBaseMapper shopGateGoodsBaseMapper;
    @Override
    public ResponseResult queryGateShopIdByUserId(Map<String, String> map) {
        ShopGateEntity entity=this.baseMapper.selectOne(new LambdaQueryWrapper<ShopGateEntity>()
                             .eq(ShopGateEntity::getUserId,map.get("userId"))
                             .or()
                             .eq(ShopGateEntity::getLoginName,map.get("userMobile")));
        return ResponseResult.success(entity);
    }

    @Override
    public Integer queryUserIsGate(String userMobile) {
        return this.baseMapper.queryUserIsGate(userMobile);
    }

    @Override
    public ResponseResult updateShopGateStock(String saleSum) {
        List<WapGoodsSaleSumUpdateVO> result = JSON.parseArray(saleSum, WapGoodsSaleSumUpdateVO.class);
        result.forEach(reS->{

            Integer integer = this.baseMapper.updateShopGateStock(reS.getGoodsNum(), reS.getCommonId(), reS.getGoodsId(), reS.getShopGateId());
        });
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryGateDetail(Map<String, Object> param) {
        Integer gateId = Integer.valueOf(param.get("shopGateId").toString());
        ShopGateEntity gateDetail =this.baseMapper.selectById(gateId);

        gateDetail.setProvinceId(gateDetail.getProvince());
        gateDetail.setCityId(gateDetail.getCity());
        gateDetail.setCountyId(gateDetail.getCounty());
        gateDetail.setProvince(baseServiceClient.queryProvinceport(gateDetail.getProvince()));
        gateDetail.setCity(baseServiceClient.queryProvinceport(gateDetail.getCity()));
        gateDetail.setCounty(baseServiceClient.queryProvinceport(gateDetail.getCounty()));
        return ResponseResult.success(gateDetail);
    }

    @Override
    public ResponseResult isShopGate(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        if(null != userInfo){
            Map<String,Object> shopGate = this.baseMapper.queryGateShopIdByUserId(userInfo.getUserId());
            return ResponseResult.success(shopGate);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
    }

    @Override
    public ResponseResult queryGateStore(GateQueryStoreDTO gateQueryStoreDTO) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(gateQueryStoreDTO.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        List<GoodsGateVO> newcommonGateDTOList=new ArrayList<>();
        List<GoodsGateVO> goodsGateDTOList = this.baseMapper.selectAppGateStore(gateQueryStoreDTO);
        goodsGateDTOList.forEach(goodsGateDTO->{
            goodsGateDTO.setCity(baseServiceClient.queryProvinceport(goodsGateDTO.getCity()));
            goodsGateDTO.setProvince(baseServiceClient.queryProvinceport(goodsGateDTO.getProvince()));
            goodsGateDTO.setCounty(baseServiceClient.queryProvinceport(goodsGateDTO.getCounty()));
        });
        for(GoodsGateVO goodsGateDTO : goodsGateDTOList){
            //店铺位置坐标
            GlobalCoordinates userSource = new GlobalCoordinates(Double.parseDouble(goodsGateDTO.getLatitude()), Double.parseDouble(goodsGateDTO.getLongitude()));
            //用户当前坐标
            GlobalCoordinates businessTarget = new GlobalCoordinates(Double.parseDouble(gateQueryStoreDTO.getLatitude().toString()), Double.parseDouble(gateQueryStoreDTO.getLongitude().toString()));
            double meterDouble = getDistanceMeter(userSource, businessTarget, Ellipsoid.Sphere);
            int meter = (int) meterDouble;
            goodsGateDTO.setDistance(Integer.valueOf(meter));
            Integer kilo = gateQueryStoreDTO.getKilo();
            if(kilo.intValue()*1000 > meter){
                newcommonGateDTOList.add(goodsGateDTO);
            }
        }
        return ResponseResult.success(newcommonGateDTOList);
    }
    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
        return geoCurve.getEllipsoidalDistance();
    }

    @Override
    public String queryGateStoreName(Integer orderGateShopId) {
        return this.baseMapper.queryGateStoreName(orderGateShopId);
    }

    @Override
    public ResponseResult openGateStore(GateOpenDTO gateOpenDTO) {
        if(gateOpenDTO.getShopGateList() != null && gateOpenDTO.getShopGateList().size() > 0) {

            UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(gateOpenDTO.getToken());
            if (userInfoVO == null) {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
            }
            //设置门店状态为：0.关闭
            for(Integer gateOpenId : gateOpenDTO.getShopGateList()) {
                //更新门店状态为1
                Integer updateGateState = this.baseMapper.update(null,new LambdaUpdateWrapper<ShopGateEntity>()
                                          .set(ShopGateEntity::getState, CommonType.commonStatus.YES.getCode())
                                          .eq(ShopGateEntity::getShopGateId,gateOpenId));
                if (updateGateState == 0) {
                    return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                }
            }
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult stopGateStore(GateOpenDTO gateOpenDTO) {
        if(gateOpenDTO.getShopGateList() != null && gateOpenDTO.getShopGateList().size() > 0){
            //根据Token获取用戶信息(shopId)
            UserInfoVO userInfoVO = ParseTokenUtils.getPlatformUser(gateOpenDTO.getToken());
            if (null==userInfoVO) {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            //设置门店状态为：0.关闭
            for(Integer gateStopDTO : gateOpenDTO.getShopGateList()){
                //查询出所有门店商品
                List<ShopGateGoodsBaseEntity> gateGoodsDTOList = shopGateGoodsBaseMapper.selectList(new LambdaQueryWrapper<ShopGateGoodsBaseEntity>()
                                                        .eq(ShopGateGoodsBaseEntity::getShopGateId,gateStopDTO));
                for(ShopGateGoodsBaseEntity gateGoodsDTO : gateGoodsDTOList){//一个商品规格更新一次
                    Integer updateBaseNum = shopGateGoodsBaseMapper.updateBaseStock(gateGoodsDTO);
                    if(updateBaseNum != 1){
                        return ResponseResult.fail(BizCodeEnume.ONLINE_PRODUCT_SPECIFICATION_INVENTORY_UPDATE_FAILED.getMsg()+gateStopDTO);

                    }
                }
                //更新门店所有 商品和规格 库存为0
                Integer updateGateCommonStock = shopGateGoodsBaseMapper.update(null,new LambdaUpdateWrapper<ShopGateGoodsBaseEntity>()
                                                .set(ShopGateGoodsBaseEntity::getShopGateGoodsStock,0)
                                                .eq(ShopGateGoodsBaseEntity::getShopGateId,gateStopDTO));
                //更新门店状态为0
                Integer updateGateState = this.baseMapper.update(null,new LambdaUpdateWrapper<ShopGateEntity>()
                                         .set(ShopGateEntity::getState, CommonType.commonStatus.NO.getCode())
                                         .eq(ShopGateEntity::getShopGateId,gateStopDTO));
                if(updateGateState == 0){
                    return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                }
            }
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult updateGateStore(GateStoreUpdateDTO gateStoreUpdateDTO) {
        if(gateStoreUpdateDTO.getToken() != null && gateStoreUpdateDTO.getToken()!="") {
            //根据Token获取用戶信息(shopId)
            UserInfoVO userInfo=ParseTokenUtils.getUserInfoByToken(gateStoreUpdateDTO.getToken());
            if(userInfo.getShopId() != null){
                Integer shopId = Integer.valueOf(userInfo.getShopId());
                gateStoreUpdateDTO.setShopId(shopId);
                if(gateStoreUpdateDTO.getLatitude() != null && gateStoreUpdateDTO.getLatitude().toString() !=""){
                    gateStoreUpdateDTO.setLatitude2(gateStoreUpdateDTO.getLatitude().toString());
                }
                if(gateStoreUpdateDTO.getLongitude() != null && gateStoreUpdateDTO.getLongitude().toString() != ""){
                    gateStoreUpdateDTO.setLongitude2(gateStoreUpdateDTO.getLongitude().toString());
                }

                Integer update = this.baseMapper.updateGateStore(gateStoreUpdateDTO);
                if(update == 1){
                    return  ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
                }else{
                    return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
                }
            }else{
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
        }else{
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

    }

    @Override
    public ResponseResult queryGateStoreByPage(GateQueryStoreDTO gateStoreQueryDTO) throws IllegalAccessException {
        if(gateStoreQueryDTO.getToken() != null && gateStoreQueryDTO.getToken()!="") {
            //根据Token获取用戶信息(shopId)
            UserInfoVO userInfo=ParseTokenUtils.getUserInfoByToken(gateStoreQueryDTO.getToken());
            if(userInfo.getShopId() != null){
                Integer shopId = Integer.valueOf(userInfo.getShopId());
                gateStoreQueryDTO.setShopId(shopId);
                Map data= ParseMapUtils.beanToMap(gateStoreQueryDTO);

                IPage<ShopGateEntity> page=this.baseMapper.queryGateStore(new Query<ShopGateEntity>().getPage(data),
                        gateStoreQueryDTO);
                if (null != page.getRecords()) {

                    page.getRecords().forEach(entity->{
                        String gateShopAddress = new String();
                        String s =baseServiceClient.queryProvinceport(entity.getCity());
                        String s1 =baseServiceClient.queryProvinceport(entity.getProvince());
                        String s2 =baseServiceClient.queryProvinceport(entity.getCounty());
                        if(null == s){
                            s = "";
                        }
                        if(null == s1){
                            s1 = "";
                        }
                        if(null == s2){
                            s2 = "";
                        }
                        gateShopAddress = s+s1+s2;
                        entity.setShopGateAddress(gateShopAddress);

                    });
                }
                return ResponseResult.success(PageUtils.getPage(page));
            }else{
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
        }else{
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
    }

    @Override
    public ResponseResult queryShopNearBy(Map<String, Object> param) {
        List<GoodsGateDTO> newcommonGateDTOList=new ArrayList<>();
        List<GoodsGateDTO> goodsGateDTOList = this.baseMapper.queryGateGoods();
        goodsGateDTOList.forEach(goodsGateDTO->{
            String s = this.baseMapper.queryAddressNameById(goodsGateDTO.getProvince());
            String s1 = this.baseMapper.queryAddressNameById(goodsGateDTO.getCity());
            String s2 = this.baseMapper.queryAddressNameById(goodsGateDTO.getCounty());
            goodsGateDTO.setCity(s1);
            goodsGateDTO.setProvince(s);
            goodsGateDTO.setCounty(s2);
        });
        for(GoodsGateDTO goodsGateDTO : goodsGateDTOList){
            List<GoodsInfoDTO> goodsInfo = this.baseMapper.queryGoodsInfo(goodsGateDTO.getShopGateId());
            goodsGateDTO.setGoodsInfo(goodsInfo);
            //店铺位置坐标
            GlobalCoordinates userSource = new GlobalCoordinates(Double.parseDouble(goodsGateDTO.getLatitude()), Double.parseDouble(goodsGateDTO.getLongitude()));
            //用户当前坐标
            GlobalCoordinates businessTarget = new GlobalCoordinates(Double.parseDouble(param.get("latitude").toString()), Double.parseDouble(param.get("longitude").toString()));
            double meterDouble = getDistanceMeter(userSource, businessTarget, Ellipsoid.Sphere);
            int meter = (int) meterDouble;
            goodsGateDTO.setDistance(meter);
            Integer kilo = (Integer) param.get("kilo");
            if(kilo *1000 > meter){
                newcommonGateDTOList.add(goodsGateDTO);
            }
        }
        return ResponseResult.success(newcommonGateDTOList);
    }

    @Override
    public ResponseResult queryGoods(Map<String, Object> param) {
        Page<GoodsInfoDTO> page = new Page<>((Integer) param.get("page"), (Integer) param.get("limit"));
        IPage<GoodsInfoDTO> result = this.baseMapper.queryGoods(page,param);
        return ResponseResult.success(PageUtils.getPage(result));
    }
}




